package com.lgx.mall.basic.dao.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.lgx.common.basic.dao.GeneralDao;
import com.lgx.common.exception.DataException;
import com.lgx.common.web.Pagination;
import com.lgx.mall.basic.dao.IFareDao;
import com.lgx.mall.basic.entity.Fare;

@Component
public class FareDao extends GeneralDao implements IFareDao {

	protected Logger log = Logger.getLogger(this.getClass());
	
	@Override
	@Transactional
	public Fare createFare(Fare fare) throws DataException {
		this.getHibernateTemplate().save(fare);
		return fare;
	}

	@Override
	@Transactional
	public Fare updateFare(Fare fare) throws DataException {
		this.getHibernateTemplate().update(fare);
		return fare;
	}

	@Override
	@Transactional
	public void deleteFare(Fare fare) throws DataException {
		this.getHibernateTemplate().delete(fare);
	}

	@Override
	public void deleteFareById(long id) throws DataException {
		this.deleteFare(this.findFareById(id));
	}

	@Override
	public void deleteFare(String[] ids) throws DataException {
		for(String id : ids){
			this.deleteFareById(Long.parseLong(id));
		}
	}

	@Override
	public Fare findFareById(long id) {
		return this.getHibernateTemplate().get(Fare.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Fare> findFareList() {
		return this.getHibernateTemplate().find("from Fare order by id asc");
	}

	@Override
	public Pagination findFarePagination(String fromCity, String toCity,
			int pageSize, int pageNum) {
		String hql = "from Fare where 1=1";
		
		if(!StringUtils.isEmpty(fromCity)){
			hql += " and fromCity like '%"+fromCity+"%'";
		}
		
		if(!StringUtils.isEmpty(toCity)){
			hql += " and toCity like '%"+toCity+"%'";
		}
		
		hql += " order by id asc";
		return this.getListPagination(hql, new Object[]{}, pageSize, pageNum);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Fare> findFareList(String fromCity,String toProvince,String toCity,String toRegion) {
		String hql = "from Fare where 1=1";
		
		if(!StringUtils.isEmpty(fromCity)){
			hql += " and fromCity like '%"+fromCity+"%'";
		}
		
		if(!StringUtils.isEmpty(toProvince)){
			hql += " and prop1 like '%"+toProvince+"%'";
		}
		
		if(!StringUtils.isEmpty(toCity)){
			hql += " and toCity like '%"+toCity+"%'";
		}
		
		if(!StringUtils.isEmpty(toRegion)){
			hql += " and prop2 like '%"+toRegion+"%'";
		}
		
		hql += " order by id asc";
		return this.getHibernateTemplate().find(hql);
	}

}
